import {request} from "../../static/core/request";
import {BASE_URL, ENV} from "../../static/core/env";

export default {
  namespaced: true,
  state: {
    token: null,
    userInfo: null,
  },
  mutations: {
    setToken(state, token) {
      state.token = token;
      if (token) {
        uni.setStorageSync("token", token);
      } else {
        uni.removeStorageSync("token");
      }
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo;
      if (userInfo) {
        uni.setStorageSync("userInfo", userInfo);
      } else {
        uni.removeStorageSync("userInfo");
      }
    }
  },
  actions: {
    login({ commit }, data) {
      return new Promise((resolve, reject) => {
        return request({
          url: '/sys/login',
          method: 'post',
          data,
        }).then(res => {
          commit("setToken", res.result.token);
          commit("setUserInfo", res.result);
          resolve();
        }).catch((err) => {
          reject(err);
        });
      });
    },
    logout({ commit }) {
      return new Promise((resolve, reject) => {
        commit("setToken", null);
        commit("setUserInfo", null);
        uni.removeStorageSync("token");
        console.log('用户退出了', this.state.token);
        resolve();
      });
    },
    saveLogin({ commit }, { token, userInfo }){
      commit("setToken", token);
      commit("setUserInfo", userInfo);
    },
    async getInfo({ commit }) {
      // if (this.state.userInfo) {
      //   return this.state.userInfo;
      // } else {
      //   try {
      //     const { data } = await request({
      //       url: "getInfo",
      //       method: "GET",
      //     });
      //     commit("setUserInfo", data);
      //     return data;
      //   } catch (err) {
      //     throw err;
      //   }
      // }
      return new Promise((resolve, reject) => {
        const userInfo = this.state.userInfo || uni.getStorageSync("userInfo") || null;
        if (userInfo) {
          resolve(userInfo);
          return
        }
        request({
          url: "getInfo",
          method: "GET",
        }).then((res) => {
          commit("setUserInfo", res);
          resolve(res);
        }).catch((err) => {
          reject(err);
        });
      });
    }
  },
  getters: {
    token: state => {
      console.log(state.token, uni.getStorageSync("token"), 999);
      return state.token || uni.getStorageSync("token") || null;
    },
    userInfo: state => {
      return state.userInfo || uni.getStorageSync("userInfo") || null;
    }
  }
}
